import os
import django
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import User
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.utils import timezone

class ProductAnalysis(models.Model):
    """产品分析结果表"""
    
    productid = models.CharField(max_length=50, db_index=True)
    market_demand = models.FloatField(null=True, blank=True, verbose_name='市场需求指数')
    competition_level = models.FloatField(null=True, blank=True, verbose_name='竞争程度指数')
    profitability = models.FloatField(null=True, blank=True, verbose_name='盈利能力指数')
    growth_potential = models.FloatField(null=True, blank=True, verbose_name='增长潜力指数')
    surge_index = models.FloatField(null=True, blank=True, verbose_name='飙升指数')
    rank_change = models.FloatField(null=True, blank=True, verbose_name='排名变化')
    sales_change = models.FloatField(null=True, blank=True, verbose_name='销量变化')
    review_change = models.FloatField(null=True, blank=True, verbose_name='评论变化')
    is_surging = models.BooleanField(default=False, verbose_name='是否飙升')
    optimized_title = models.CharField(max_length=500, null=True, blank=True, verbose_name='优化后的标题')
    optimized_bullets = models.TextField(null=True, blank=True, verbose_name='优化后的五点描述(JSON格式)')
    keyword_suggestions = models.TextField(null=True, blank=True, verbose_name='关键词建议(JSON格式)')
    confidence_score = models.FloatField(null=True, blank=True, verbose_name='置信度分数')
    analysis_date = models.DateTimeField(default=timezone.now, verbose_name='分析日期')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    epid = models.CharField(verbose_name='部门编号', max_length=64, db_index=True, null=True, blank=True)
    permissions = [
            ("can_manage_productanalysis_admin",
             "Can manage productanalysis in admin"),
        ]
    class Meta:
        verbose_name = '产品分析'
        verbose_name_plural = '产品分析'
        ordering = ['-analysis_date']
        db_table = 'app_product_analysis'
        app_label = 'app'  # 添加这一行，确保模型与应用关联

    def __str__(self):
        return f'产品分析 - {self.productid}'

    @property
    def product(self):
        """关联产品"""
        from .models import ProductXue
        return ProductXue.objects.filter(productid=self.productid).first()

    @classmethod
    def get_latest_analysis(cls, productid):
        """获取产品最新的分析结果"""
        return cls.objects.filter(productid=productid).order_by('-analysis_date').first()

    @classmethod
    def get_surging_products(cls, limit=10):
        """获取飙升产品列表"""
        return cls.objects.filter(is_surging=True).order_by('-surge_index')[:limit]

    @classmethod
    def get_market_metrics(cls):
        """获取市场指标"""
        from django.db.models import Avg
        metrics = cls.objects.aggregate(
            avg_market_demand=Avg('market_demand'),
            avg_competition_level=Avg('competition_level'),
            avg_profitability=Avg('profitability')
        )
        
        return {
            'market_demand': metrics['avg_market_demand'] or 0,
            'competition_level': metrics['avg_competition_level'] or 0,
            'profitability': metrics['avg_profitability'] or 0
        }
 

class asinsmonitor_xue(models.Model):
    id = models.AutoField('ASIN编号',  primary_key=True)
    asin = models.CharField('ASIN', max_length=64, null=False)
    hoursdiff = models.IntegerField('监控频率：小时', null=False)
    opdate = models.DateTimeField('更新时间', auto_now=True)
    epid = models.CharField('部门编号', max_length=64, null=False)
    processdate=models.DateTimeField('处理时间', null=True, blank=True)
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)

    class Meta:
        db_table = 'app_asinsmonitor_xue'
        verbose_name = "ASIN监控"
        app_label = 'app'  # 添加这一行
    permissions = [
            ("can_manage_asinsmonitor_admin", "can manage asinsmonitor in admin"),
        ]

class CategoryXue(models.Model):
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)

    id = models.AutoField('分类编号', primary_key=True)
    category = models.CharField('分类', max_length=64, null=False)
    parent_category = models.CharField('父分类', max_length=64, null=False)
    leaf_category = models.BooleanField('是否为叶子分类', default=False)
    parent_level = models.CharField('父分类级别', max_length=64, null=False)
    level = models.CharField('分类级别', max_length=64, null=False)
    url = models.CharField('分类链接', max_length=64, null=False)
    image_url = models.CharField('图片链接', max_length=64, null=False)
    alt_text = models.CharField('alt文本', max_length=64, null=False)
    currentpage = models.CharField('当前页', max_length=64, null=False)
    opdate = models.DateTimeField('更新时间', auto_now=True)
    need_download = models.BooleanField('是否需要下载', default=False)
    permissions = [
            ("can_manage_category_admin",'can manage category in admin'),
        ]
    class Meta:
        db_table = 'app_category_xue'
        verbose_name = "亚马逊分类"
        verbose_name_plural = "亚马逊分类"
        app_label = 'app'  # 添加这一行
    
class upc_xue(models.Model):
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)

    id = models.AutoField('UPC编号', primary_key=True)
    upc = models.CharField('UPC', max_length=64, null=False)
    created_at = models.DateTimeField('创建时间', auto_now_add=True, blank=True)
    upload_at = models.DateTimeField('使用时间', auto_now_add=True, blank=True)
    epid = models.CharField('部门编号', max_length=64, null=False)
    permissions = [
            ("can_manage_upc_admin",'can manage upc in admin'),
        ]

    class Meta:
        db_table = 'app_upc_xue'
        app_label = 'app'  # 添加这一行

class ShopWhiteList(models.Model):
    id = models.AutoField('白名单编号', primary_key=True)
    # shop_type = models.CharField('店铺类型', max_length=64, null=False)
    shop_type_choice = (
        ('ebay', 'ebay.com店铺'),
        ('ali', 'aliexpress.com店铺'),
    )
    shop_type = models.CharField('店铺类别',
                                 max_length=20,
                                 choices=shop_type_choice)
    shop_name = models.CharField('店铺名称', max_length=64, null=False)
    class Meta:
        db_table = 'shopwhite_list' 
        app_label = 'app'  # 添加这一行
 
 

class FollowPriceXue(models.Model):
    id = models.AutoField('跟踪编号', primary_key=True)
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)
     
    storename = models.CharField('店铺', max_length=64, null=False, default='Amazon')
    username = models.CharField('负责人', max_length=64, null=False)
    keywords = models.CharField('关键词', max_length=800, null=False)
    downloaddetailatonce = models.BooleanField('是否立刻下载详情页',default=False)
    timestamp = models.IntegerField('创建时间戳', blank=True, default=0)
    shop_type_choice = (
        ('amazon', 'amazon.com店铺'),
        ('walmart', 'walmart.com店铺'),
    )
    shop_type = models.CharField('店铺类别',
                                 max_length=20,
                                 choices=shop_type_choice)
    title = models.CharField('标题', max_length=800, null=False)
    title2 = models.CharField('标题2', max_length=800, null=True, blank=True)
    newtitle = models.CharField('标题-ai生成', max_length=800, null=True, blank=True)
    link = models.CharField('链接', max_length=2000, null=False)  # 增加长度以适应亚马逊长链接
    main_image = models.CharField('主图路径', max_length=255, blank=True)
    price = models.CharField('美元价格', max_length=64, null=False)
    currency = models.CharField('网站显示货币', max_length=64, null=True, default='USD')
    salesvolume = models.FloatField('销量', null=True, blank=True)  # 亚马逊可能没有具体销量

    salesvolume2 = models.FloatField('销量2', null=True, blank=True)
    main_image2 = models.CharField('图片2', max_length=800, null=True, blank=True)
    price2 = models.CharField('价格2', max_length=64, null=True, blank=True)
    itemid = models.CharField('ASIN', max_length=255, blank=True, null=True)  # 重命名为ASIN
    productid = models.CharField('平台产品编号',max_length=255, blank=True, null=True)
    lowvalue = models.CharField('跟价最低价格', max_length=64, null=False)
    opdate = models.DateTimeField('操作日期', auto_now=False, auto_now_add=True)
    last_detaildownload_date = models.DateTimeField('最后详情页下载日期', null=True, blank=True)
    followstatus = models.CharField('跟价状态',
                                    max_length=64,
                                    default='未跟价',
                                    null=True)
    memo = models.CharField('备注', max_length=800, null=True, blank=True)
    
    # 新增字段
    rating = models.FloatField('评分', null=True, blank=True)  # 商品评分
    prime = models.BooleanField('Prime商品', default=False)  # 是否为Prime商品
    seller = models.CharField('卖家', max_length=200, null=True, blank=True)  # 卖家信息
    parent_asin = models.CharField('父ASIN', max_length=255, blank=True, null=True)  # 新增
    variation_attributes = models.CharField('变体属性', max_length=200, null=True, blank=True)  # 新增
    bullet_points = models.CharField('产品要点', max_length=200, null=True, blank=True)  # 新增
    technical_details = models.CharField('技术细节', max_length=200, null=True, blank=True)  # 新增
    best_sellers_rank = models.CharField('畅销排名', max_length=200, null=True, blank=True)  # 新增
    is_amazon_choice = models.BooleanField('Amazon推荐', default=False)  # 新增
    is_prime_exclusive = models.BooleanField('Prime专享', default=False)  # 新增
    fulfillment_type = models.CharField('配送类型', max_length=50, null=True, blank=True)  # 新增
    warehouse_location = models.CharField('仓库位置', max_length=200, null=True, blank=True)  # 新增
    aplus_content = models.TextField('A+内容', null=True, blank=True)  # 新增
    buybox_winner = models.CharField('黄金购物车卖家', max_length=200, null=True, blank=True)  # 新增
    offer_count = models.IntegerField('报价数量', null=True, blank=True)  # 新增
    variation_count = models.IntegerField('变体数量', null=True, blank=True)  # 新增
    last_price_change = models.DateTimeField('最后价格变动时间', null=True, blank=True)  # 新增
    is_captcha = models.BooleanField('触发验证', default=False)  # 新增反爬验证状态字段
    capturedatetowalmart=models.DateTimeField('沃尔玛抓取时间', null=True, blank=True)
    # 修改现有字段增强亚马逊适配性
    uploadtowalmartdate=models.DateTimeField('沃尔玛上传时间', null=True, blank=True)
    price = models.DecimalField('美元价格', max_digits=10, decimal_places=2, null=True)  # 改为Decimal类型
    rating = models.DecimalField('评分', max_digits=3, decimal_places=1, null=True, blank=True)  # 改为3.1分格式
    reviews_count = models.IntegerField('评论数', null=True, blank=True)  # 改为3.1分格式
    last_price_change = models.DateTimeField('最后价格变动时间', null=True, blank=True)
    can_pubished=models.BooleanField('是否可上新',default=False )
    sales_info=models.CharField('销量信息', max_length=200, null=True, blank=True)  # 改为结构化存储
    badges=models.CharField('徽章信息', max_length=200, null=True, blank=True)  # 改为结构化存储
    delivery_info=models.CharField('配送信息', max_length=200, null=True, blank=True)  # 改为结构化存储
    brand=models.CharField('品牌信息', max_length=200, null=True, blank=True)  # 改为结构化存储
    category=models.CharField('商品分类', max_length=200, null=True, blank=True)  # 存储多级分类
    seller=models.CharField('卖家信息', max_length=200, null=True, blank=True)  # 改为结构化存储
    in_stock=models.BooleanField('是否在仓库里',default=True )
    mainpic=models.CharField('主图', max_length=200, null=True, blank=True)
    pic=models.CharField('主图', max_length=200, null=True, blank=True)
    image1 = models.CharField('图片1路径', max_length=255, blank=True)
    image2 = models.CharField('图片2路径', max_length=255, blank=True)
    image3 = models.CharField('图片3路径', max_length=255, blank=True)
    image4 = models.CharField('图片4路径', max_length=255, blank=True)
    image5 = models.CharField('图片5路径', max_length=255, blank=True)
    image6 = models.CharField('图片6路径', max_length=255, blank=True)
    image7 = models.CharField('图片7路径', max_length=255, blank=True)


    detail1=models.CharField('5点描述1', max_length=2000, null=True, blank=True)
    detail2=models.CharField('5点描述2', max_length=2000, null=True, blank=True)
    detail3=models.CharField('5点描述3', max_length=2000, null=True, blank=True)
    detail4=models.CharField('5点描述4', max_length=200, null=True, blank=True)
    detail5=models.CharField('5点描述5', max_length=200, null=True, blank=True)

    length=models.FloatField('长度', null=True, blank=True)
    width=models.FloatField('宽度', null=True, blank=True)
    height=models.FloatField('高度', null=True, blank=True)
    lengthunit=models.CharField('长度单位', max_length=200, null=True, blank=True)
    weight=models.FloatField('重量', null=True, blank=True)
    weightunit=models.CharField('重量单位', max_length=200, null=True, blank=True)

    Department=models.CharField('部门', max_length=200, null=True, blank=True)
    publishdate=models.CharField('发布日期', max_length=200, null=True, blank=True)
    Manufacturer=models.CharField('制造商', max_length=200, null=True, blank=True)
    main_rank=models.CharField('主排名', max_length=200, null=True, blank=True)
    maincategory=models.CharField('主分类', max_length=200, null=True, blank=True)
    sub_rank=models.CharField('子排名', max_length=200, null=True, blank=True)
    sun_subcategory=models.CharField('子分类', max_length=200, null=True, blank=True)
    product_dimensions=models.CharField('产品尺寸', max_length=200, null=True, blank=True)
    best_sellers_rank=models.CharField('畅销排名', max_length=200, null=True, blank=True)
    item_model_number=models.CharField('产品型号', max_length=200,  null=True, blank=True)
    @property
    def safe_itemid(self):
        return self.itemid or ''
        permissions = [
            ("can_manage_followprice_admin",
             "Can manage followprice in admin"),
        ]
    class Meta:
        db_table = 'app_product_xue'
        verbose_name = 'amazon链接'
        verbose_name_plural = 'amazon链接'    
        indexes = [
            models.Index(fields=['itemid']),
            models.Index(fields=['parent_asin']),
            models.Index(fields=['brand']),
        ]
        app_label = 'app'  # 添加这一行


class FollowPrice_lucas(models.Model):
    id = models.AutoField('跟踪编号', primary_key=True)
    shop_type_choice = (
        ('ebay', 'ebay.com店铺'),
        ('ali', 'aliexpress.com店铺'),
    )
    shop_type = models.CharField('店铺类别',
                                 max_length=20,
                                 choices=shop_type_choice)
    storename = models.CharField('店铺', max_length=64, null=False)
    username = models.CharField('负责人', max_length=64, null=False)
    keywords = models.CharField('关键词', max_length=800, null=False)

    title = models.CharField('标题', max_length=800, null=False)
    title2 = models.CharField('标题2', max_length=800, null=True)
    link = models.CharField('链接', max_length=800, null=False)
    pic = models.CharField('图片', max_length=800, null=True)
    price = models.CharField('美元价格', max_length=64, null=False)
    currency = models.CharField('网站显示货币', max_length=64, null=True)
    salesvolume = models.FloatField('销量', max_length=64, null=True)

    salesvolume2 = models.FloatField('销量2', max_length=64, null=True)
    pic2 = models.CharField('图片2', max_length=800, null=True)
    price2 = models.CharField('价格2', max_length=64, null=True)
    itemid = models.CharField(max_length=255, blank=True, null=True)
    productid = models.CharField('平台产品编号',max_length=255, blank=True, null=True)
    lowvalue = models.CharField('跟价最低价格', max_length=64, null=False)
    opdate = models.DateTimeField('操作日期', auto_now=False, auto_now_add=True)
    followstatus = models.CharField('跟价状态',
                                    max_length=64,
                                    default='未跟价',
                                    null=True)
    memo = models.CharField('备注', max_length=800, null=True)
    @property
    def safe_itemid(self):
        return self.itemid or ''
    class Meta:
        db_table = 'follow_price_lucas'
        verbose_name = 'ebay多平台产品资料'
        verbose_name_plural = 'ebay多平台产品资料'
        permissions = [
            ("can_manage_followprice_admin",
             "Can manage followprice in admin"),
        ]
 
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text, DECIMAL, ForeignKey
from sqlalchemy.sql import text
from sqlalchemy.ext.declarative import declarative_base

from django.db import models
class AmazonOrder2(models.Model):
    amazon_order_id = models.CharField(max_length=255, unique=True, verbose_name='Amazon订单ID')
    seller_order_id = models.CharField(max_length=255, null=True, blank=True, verbose_name='卖家订单ID')
    purchase_date = models.DateTimeField(null=True, blank=True, verbose_name='购买日期')
    last_update_date = models.DateTimeField(null=True, blank=True, verbose_name='最后更新日期')
    order_status = models.CharField(max_length=50, null=True, blank=True, verbose_name='订单状态')
    fulfillment_channel = models.CharField(max_length=50, null=True, blank=True, verbose_name='履约渠道')
    sales_channel = models.CharField(max_length=100, null=True, blank=True, verbose_name='销售渠道')
    ship_service_level = models.CharField(max_length=100, null=True, blank=True, verbose_name='配送服务等级')
    shipment_service_level_category = models.CharField(max_length=100, null=True, blank=True, verbose_name='配送服务类别')
    number_of_items_shipped = models.IntegerField(default=0, verbose_name='已配送物品数量')
    number_of_items_unshipped = models.IntegerField(default=0, verbose_name='未配送物品数量')
    payment_method = models.CharField(max_length=50, null=True, blank=True, verbose_name='支付方式')
    payment_method_details = models.TextField(null=True, blank=True, verbose_name='支付详情')
    marketplace_id = models.CharField(max_length=100, null=True, blank=True, verbose_name='市场ID')
    order_type = models.CharField(max_length=50, null=True, blank=True, verbose_name='订单类型')
    earliest_ship_date = models.DateTimeField(null=True, blank=True, verbose_name='最早配送日期')
    latest_ship_date = models.DateTimeField(null=True, blank=True, verbose_name='最晚配送日期')
    is_business_order = models.BooleanField(default=False, verbose_name='是否企业订单')
    is_prime = models.BooleanField(default=False, verbose_name='是否Prime订单')
    is_premium_order = models.BooleanField(default=False, verbose_name='是否高级订单')
    is_global_express_enabled = models.BooleanField(default=False, verbose_name='是否启用全球快递')
    is_replacement_order = models.BooleanField(default=False, verbose_name='是否替换订单')
    is_sold_by_ab = models.BooleanField(default=False, verbose_name='是否通过AB销售')
    is_ispu = models.BooleanField(default=False, verbose_name='是否ISPU')
    is_access_point_order = models.BooleanField(default=False, verbose_name='是否访问点订单')
    has_regulated_items = models.BooleanField(default=False, verbose_name='是否包含管制物品')
    buyer_email = models.CharField(max_length=255, null=True, blank=True, verbose_name='买家邮箱')
    currency_code = models.CharField(max_length=10, null=True, blank=True, verbose_name='货币代码')
    order_total_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='订单总金额')
    shipping_address_state = models.CharField(max_length=100, null=True, blank=True, verbose_name='配送地址州/省')
    shipping_address_postal_code = models.CharField(max_length=20, null=True, blank=True, verbose_name='配送地址邮编')
    shipping_address_city = models.CharField(max_length=100, null=True, blank=True, verbose_name='配送地址城市')
    shipping_address_country_code = models.CharField(max_length=10, null=True, blank=True, verbose_name='配送地址国家代码')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'app_orders_amz'  # 指定与SQLAlchemy模型相同的表名
        verbose_name = 'Amazon订单'
        verbose_name_plural = 'Amazon订单'
        ordering = ['-purchase_date']
    
    def __str__(self):
        return f"Amazon订单 {self.amazon_order_id}"
     
class AmazonOrderItem2(models.Model):
    id = models.AutoField(primary_key=True)
    order = models.ForeignKey(AmazonOrder2, on_delete=models.CASCADE, related_name='items', verbose_name='所属订单')
    asin = models.CharField(max_length=50, verbose_name='ASIN')
    seller_sku = models.CharField(max_length=50, null=True, blank=True, verbose_name='卖家SKU')
    order_item_id = models.CharField(max_length=50, unique=True, verbose_name='订单项目ID')
    title = models.CharField(max_length=500, null=True, blank=True, verbose_name='商品标题')
    quantity_ordered = models.IntegerField(default=0, verbose_name='订购数量')
    quantity_shipped = models.IntegerField(default=0, verbose_name='已发货数量')
    item_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='商品价格')
    item_price_currency = models.CharField(max_length=10, null=True, blank=True, verbose_name='商品价格货币')
    item_tax = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='商品税费')
    shipping_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='运费')
    shipping_tax = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='运费税')
    promotion_discount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='促销折扣')
    condition = models.CharField(max_length=50, null=True, blank=True, verbose_name='商品状况')
    condition_note = models.TextField(null=True, blank=True, verbose_name='状况说明')
    is_gift = models.BooleanField(default=False, verbose_name='是否礼品')
    gift_message = models.TextField(null=True, blank=True, verbose_name='礼品消息')
    gift_wrap_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='礼品包装费')
    created_at = models.DateTimeField(auto_now=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        managed = False  # 告诉Django不要管理这个表
        db_table = 'app_order_items_amz'  # 使用与SQLAlchemy相同的表名
        verbose_name = 'Amazon订单项目'
        verbose_name_plural = 'Amazon订单项目'
    
    def __str__(self):
        return f"{self.order.amazon_order_id} - {self.asin}"
class SkuKeywords_lucas(models.Model):
    username = models.CharField('创建人', max_length=64, null=True)

    id = models.AutoField('关键词编号', primary_key=True)
    keywords = models.CharField('关键词', max_length=64, null=False, default='')
    sku = models.CharField('sku编码（不用录入）', max_length=64,blank=True, default='', null=True)

    chargeman = models.CharField('负责人（不用录入）', max_length=64,blank=True, null=True, default='')

    lowvalue = models.FloatField('跟价最低金额（不用录入）', null=True, default=0)
    ebay = models.BooleanField('ebay.com店铺', null=True, default=True)
    ali = models.BooleanField('aliexpress.com店铺', null=True, default=True)
    amz = models.BooleanField('amazon.com店铺', null=True, default=True)
    followstatus = models.CharField('是否跟价过竞品',
                                    max_length=64,
                                    default='未跟价',
                                    null=True)
    captured = models.CharField('抓取状态',default='未抓取', max_length=64, null=True)
    opdate = models.DateTimeField('更新时间', auto_now=True)
    download_date    = models.DateTimeField('下载日期',default=None, blank=True, null=True)
    def save(self, *args, **kwargs):
        if not self.username and hasattr(self, '_current_user'):
            self.username = self._current_user.username
        super().save(*args, **kwargs)
    class Meta:
        db_table = 'app_keywords_lucas'
        verbose_name = "ebay多平台关键词"
        verbose_name_plural = "ebay多平台关键词" 
        
class SkuKeywordsXue(models.Model):
    id = models.AutoField('编号', primary_key=True)

    username = models.CharField('创建人', max_length=64, null=True)
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)

    id = models.AutoField('关键词编号', primary_key=True)
    keywords = models.CharField('关键词', max_length=64, null=False, default='')
    shop_type_choice = (
        ('amazon', 'amazon.com店铺'),
        
    )
    shop_type = models.CharField('店铺类别',
                                 max_length=20,
                                 choices=shop_type_choice,default='amazon')
    opdate = models.DateTimeField('更新时间', auto_now=True)
    downloaddetailatonce = models.BooleanField('是否立刻下载详情页',default=False)
    detaildownfrequency = models.IntegerField('详情页下载频率(天)',default=1)
    productcounts=models.IntegerField('产品数量',default=0,blank=True,null=True)
    download_date    = models.DateTimeField('下载日期',default=None, blank=True, null=True)
    def save(self, *args, **kwargs):
        if not self.username and hasattr(self, '_current_user'):
            self.username = self._current_user.username
        super().save(*args, **kwargs)
    permissions = [
            ("can_manage_keywords_admin",
             "Can manage keywords in admin"),
        ]
    class Meta:
        db_table = 'app_keywords_xue'
        verbose_name = "关键词sku名单"
        verbose_name_plural = "输入关键词，可以下载amazon平台产品"
        app_label = 'app'  # 添加这一行




class Rates(models.Model):
    id = models.AutoField('汇率编号', primary_key=True)
    currency_name = models.CharField('货币名称', max_length=64, null=True)
    currency_simplename = models.CharField('货币简称-需要和网站一致',
                                           max_length=64,
                                           null=True)
    rate = models.FloatField('汇率', max_length=64, null=True)
    opdate = models.DateTimeField('更新时间', auto_now=True)
    permissions = [
            ("can_manage_rates_admin",
             "Can manage rates in admin"),
        ]
    class Meta:
        db_table = 'rates'
        verbose_name = "货币汇率列"
        verbose_name_plural = '当前主流货币汇率列表'
        app_label = 'app'  # 添加这一行

class PriceHistory(models.Model):
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)

    product = models.ForeignKey(FollowPriceXue, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    timestamp = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'app_price_history'
        verbose_name = "价格历史"
        verbose_name_plural = "价格历史"
        app_label = 'app'  # 将app_label放入Meta类中
    permissions = [
            ("can_manage_pricehistory_admin","can manage pricehistory in admin"),
        ]

class CrawlExcept(models.Model):
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)

    id = models.AutoField('异常编号', primary_key=True)
    shop_type_choice = (
        ('ebay', 'ebay.com店铺'),
        ('ali', 'aliexpress.com店铺'),
    )
    opdate = models.DateTimeField('操作日期', auto_now=False, auto_now_add=False, null=True)

    shop_type = models.CharField('关键词类别',
                                 max_length=20,
                                 choices=shop_type_choice)
    keywords = models.CharField('关键词', max_length=64, null=True)
    exceptcon = models.CharField('异常信息 ', max_length=2000, null=True)
    permissions = [
            ("can_manage_crawlexcept_admin",
             "Can manage crawlexcept in admin"),
        ]
    class Meta:
        db_table = 'crawlexcept'
        verbose_name = "下载异常"
        app_label = 'app'  # 添加这一行

import django.utils.timezone as timezone
@receiver(pre_save, sender=FollowPriceXue)
def check_price_change(sender, instance, **kwargs):
    if instance.pk:
        original = sender.objects.get(pk=instance.pk)
        if original.price != instance.price:
            instance.last_price_change = timezone.now()

class PriceChange(models.Model):
    id = models.AutoField('编号', primary_key=True)

    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)

    productid = models.CharField("产品ID",max_length=255     )
    old_price = models.DecimalField("旧价格",max_digits=10, decimal_places=2, )
    new_price = models.DecimalField("新价格",max_digits=10, decimal_places=2, )
    opdate = models.DateField("操作日期")

    def __str__(self):
        return f"{self.productid} - Old Price: {self.old_price}, New Price: {self.new_price}"
    permissions = [
            ("can_manage_pricechange_admin",
             "Can manage pricechange in admin"),
        ]
    class Meta:
        verbose_name = "价格变动"
        verbose_name_plural = "价格变动"
        db_table = 'app_pricechange_xue'      
        app_label = 'app'  # 添加这一行

class RankChange(models.Model):
    id = models.AutoField('编号', primary_key=True)

    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)

    productid = models.CharField("产品ID",max_length=255, )
    old_main_rank = models.IntegerField("旧主类目排名")
    new_main_rank = models.IntegerField("新主类目排名")
    old_sub_rank = models.IntegerField("旧子类目排名")
    new_sub_rank = models.IntegerField("新子类目排名")
    old_sales_info = models.CharField("旧销售数量",max_length=255, )
    new_sales_info = models.CharField("新销售数量",max_length=255, )
    old_rating = models.FloatField("旧评分")
    new_rating = models.FloatField("新评分")
    old_reviews_count = models.IntegerField("旧评论数")
    new_reviews_count = models.IntegerField("新评论数")
    opdate = models.DateField("操作日期")

    def __str__(self):
        return f"{self.productid} - Old Rank: {self.old_main_rank}, New Rank: {self.new_main_rank}"
    permissions = [
            ("can_manage_rankchange_admin",
             "Can manage rankchange in admin"),
        ]
    class Meta:
        verbose_name = "排名变动"
        verbose_name_plural = "排名变动"
        db_table = 'app_rankchange_xue'
        app_label = 'app'  # 添加这一行

class CategoryDefault(models.Model):
    id = models.AutoField('编号', primary_key=True)

    label=models.CharField('属性名称',max_length=255,null=True,blank=True)
    inputvalue=models.CharField('默认值',max_length=255,null=True,blank=True)
    input_type_choice = (
        ('select', '下拉框'),
        ('input', '输入框'),
    )
    platform_choice = (
       
        ('walmart', 'walmart'),
        ('titkok', 'titkok'),     
         ('temu', 'temu'),  
    )
    input_type = models.CharField('类型',
                                 max_length=20,
                                 choices=input_type_choice,default='input')
    platform = models.CharField('平台',
                                 max_length=20,
                                 choices=platform_choice,default='walmart')
    created_at=models.DateTimeField('创建时间',auto_now_add=True)
    updated_at=models.DateTimeField('更新时间',auto_now=True)
    option_index=models.IntegerField('排序-从0开始',default=0)
    epid = models.CharField('部门编号', max_length=64, null=False)
    permissions = [
            ("can_manage_categorydefault_admin",
             "Can manage categorydefault in admin"),
        ]
    class Meta:
        db_table = 'app_categorydefault_xue'
        verbose_name = "类目默认值"
        verbose_name_plural = "类目默认值"
        app_label = 'app'  # 添加这一行

class UserProfile(models.Model):
    """
    用户资料扩展模型 - 存储部门信息
    """
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=False, blank=False)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '用户资料'
        verbose_name_plural = '用户资料'
        db_table = 'app_user_profile'
        app_label = 'app'

    def __str__(self):
        return f"{self.user.username} - 部门: {self.epid}"

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    """
    当User对象被创建时，自动创建对应的UserProfile
    """
    if created:
        UserProfile.objects.create(user=instance, epid='default') # 默认值，之后可以修改

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    """
    当User对象被保存时，自动保存对应的UserProfile
    """
    if hasattr(instance, 'profile'):
        instance.profile.save()
    else:
        UserProfile.objects.create(user=instance, epid='default')

class AmazonProductDisplay(models.Model):
    id = models.AutoField('编号', primary_key=True)
    item_name = models.CharField('产品名称', max_length=255)
    item_description = models.TextField('产品描述')
    listing_id = models.CharField('listing ID', max_length=255)
    seller_sku = models.CharField('卖家SKU', max_length=255)
    price = models.CharField('价格', max_length=255)
    quantity = models.CharField('库存数量', max_length=255)
    open_date = models.DateTimeField('上架日期')
    image_url = models.CharField('图片URL', max_length=255)
    item_is_marketplace = models.CharField('是否市场', max_length=255)
    product_id_type = models.CharField('产品ID类型', max_length=255)
    zshop_shipping_fee = models.CharField('Zshop运费', max_length=255)
    item_note = models.CharField('产品备注', max_length=255)
    item_condition = models.CharField('产品条件', max_length=255)
    zshop_category1 = models.CharField('Zshop类目1', max_length=255)
    zshop_browse_path = models.CharField('Zshop浏览路径', max_length=255)
    zshop_storefront_feature = models.CharField('Zshop店铺特色', max_length=255)
    asin1 = models.CharField('asin1', max_length=255)
    asin2 = models.CharField('asin2', max_length=255)
    asin3 = models.CharField('asin3', max_length=255)
    will_ship_internationally = models.CharField('是否国际运输', max_length=255)
    expedited_shipping = models.CharField('加速运输', max_length=255)
    zshop_boldface = models.CharField('Zshop粗体', max_length=255)
    product_id = models.CharField('产品ID', max_length=255)
    bid_for_featured_placement = models.CharField('竞价', max_length=255)
    add_delete = models.CharField('添加删除', max_length=255)
    pending_quantity = models.CharField('待处理数量', max_length=255)
    fulfillment_channel = models.CharField('履行渠道', max_length=255)
    merchant_shipping_group = models.CharField('商家运输组', max_length=255)
    status = models.CharField('状态', max_length=255)
    updated_at = models.DateTimeField('更新时间') 
    
    
    bullet_point1 = models.CharField('bullet_point1', max_length=255)
    bullet_point2 = models.CharField('bullet_point2', max_length=255)
    bullet_point3 = models.CharField('bullet_point3', max_length=255)
    bullet_point4 = models.CharField('bullet_point4', max_length=255)
    bullet_point5 = models.CharField('bullet_point5', max_length=255)
    bullet_point6 = models.CharField('bullet_point6', max_length=255)
    bullet_point7 = models.CharField('bullet_point7', max_length=255)
    bullet_point8 = models.CharField('bullet_point8', max_length=255)
    bullet_point9 = models.CharField('bullet_point9', max_length=255)
    bullet_point10 = models.CharField('bullet_point10', max_length=255)

    brand = models.CharField('品牌', max_length=255) 
    battery_required = models.BooleanField('电池要求', default=False)
    item_package_dimensions = models.CharField('产品尺寸', max_length=255)
    item_package_weight = models.CharField('产品重量', max_length=255)
    number_of_items = models.IntegerField('数量')
    material = models.CharField('材质', max_length=255)
    unit_count = models.IntegerField('单位数量')
    color = models.CharField('颜色', max_length=255) 
    item_type_keywords = models.CharField('产品类型关键词', max_length=255)
        
    
    image2 = models.CharField('图片2', max_length=255)
    image3 = models.CharField('图片3', max_length=255)
    image4 = models.CharField('图片4', max_length=255)
    image5 = models.CharField('图片5', max_length=255)
    image6 = models.CharField('图片6', max_length=255)
    image7 = models.CharField('图片7', max_length=255)
    image8 = models.CharField('图片8', max_length=255)
    image9 = models.CharField('图片9', max_length=255)
    image10 = models.CharField('图片10', max_length=255)

 
    category1 = models.CharField('类目1', max_length=255)
    category2 = models.CharField('类目2', max_length=255)
    category3 = models.CharField('类目3', max_length=255)
    rank1 = models.IntegerField('排名1')
    rank2 = models.IntegerField('排名2') 
    rank3 = models.IntegerField('排名3')

    category_p1=models.CharField('类目1', max_length=255)
    category_p2=models.CharField('类目2', max_length=255)
    category_p3=models.CharField('类目3', max_length=255) 
     
    
 
    class Meta:
        db_table = 'app_product_amz'  # 使用与SQLAlchemy相同的表名
        verbose_name = '亚马逊Listing'
        verbose_name_plural = '亚马逊Listing'
        ordering = ['-updated_at']
        app_label = 'app'  # 添加这一行
    def __str__(self):
        return f"{self.asin1} - {self.item_name}"

class LogHistory(models.Model):
    obj = models.CharField(max_length=2000, null=True, blank=True)
    action = models.CharField(max_length=200, null=True, blank=True)
    opdate = models.DateTimeField(null=True, blank=True)
    diskid = models.CharField(max_length=200, null=True, blank=True)

    class Meta:
        db_table = 'las_loghistory'  # 指定数据库表名
        ordering = ['-opdate']  # 按操作日期降序排列

    def __str__(self):
        return f"{self.obj} - {self.action} at {self.opdate}"
class asinsupload_xue(models.Model):
    shop_type_choice = (
        ('ebay', 'ebay.com店铺'),
        ('amazon', 'amazon.com店铺'),
        ('walmart', 'walmart.com店铺'),
    )
    shop_type = models.CharField('店铺类别',
                                 max_length=20,
                                 choices=shop_type_choice)
    trytimes = models.IntegerField('尝试次数', default=0)
    asin = models.CharField('产品编号', max_length=64, null=False)
    id=models.AutoField('ASIN编号',primary_key=True)
    opdate = models.DateTimeField('下载时间', auto_now=True)
    epid = models.CharField('部门编号', max_length=64, null=False)
    processdate=models.DateTimeField('抓取时间', null=True, blank=True)
    detail1=models.CharField('5点描述1', max_length=2000, null=True, blank=True)
    detail2=models.CharField('5点描述2', max_length=2000, null=True, blank=True)
    detail3=models.CharField('5点描述3', max_length=2000, null=True, blank=True)
    detail4=models.CharField('5点描述4', max_length=2000, null=True, blank=True)
    detail5=models.CharField('5点描述5', max_length=2000, null=True, blank=True)
    image_url=models.CharField('图片链接', max_length=2000, null=True, blank=True)
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)
    
    brand = models.CharField('品牌', max_length=255) 
    battery_required = models.BooleanField('电池要求', default=False)
    item_package_dimensions = models.CharField('产品尺寸', max_length=255)
    item_package_weight = models.CharField('产品重量', max_length=255)
    number_of_items = models.IntegerField('数量')
    material = models.CharField('材质', max_length=255)
    unit_count = models.IntegerField('单位数量')
    color = models.CharField('颜色', max_length=255) 
    item_type_keywords = models.CharField('产品类型关键词', max_length=255)
        
    
    image2 = models.CharField('图片2', max_length=255)
    image3 = models.CharField('图片3', max_length=255)
    image4 = models.CharField('图片4', max_length=255)
    image5 = models.CharField('图片5', max_length=255)
    image6 = models.CharField('图片6', max_length=255)
    image7 = models.CharField('图片7', max_length=255)
    image8 = models.CharField('图片8', max_length=255)
    image9 = models.CharField('图片9', max_length=255)
    image10 = models.CharField('图片10', max_length=255)

 
    category1 = models.CharField('类目1', max_length=255)
    category2 = models.CharField('类目2', max_length=255)
    category3 = models.CharField('类目3', max_length=255)
    rank1 = models.IntegerField('排名1')
    rank2 = models.IntegerField('排名2') 
    rank3 = models.IntegerField('排名3')

    category_p1=models.CharField('类目1', max_length=255)
    category_p2=models.CharField('类目2', max_length=255)
    category_p3=models.CharField('类目3', max_length=255) 
    class Meta:
        db_table = 'app_asinsupload_xue'  # 使用与SQLAlchemy相同的表名
        verbose_name = '亚马逊asin/ebay/walmart产品上传'
        verbose_name_plural = '亚马逊asin/ebay/walmart产品上传'
        app_label = 'app'  # 添加这一行
    
from django.db import models
from django.utils import timezone


 
class Buyer(models.Model):
    amazon_buyer_id = models.CharField(max_length=64, unique=True)
    display_name = models.CharField(max_length=255, blank=True, null=True)
    email = models.EmailField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    class Meta:
        db_table = 'app_buyer'
        verbose_name = '买家'
        verbose_name_plural = '买家'
        app_label = 'app'  # 添加这一行
    def __str__(self):

        return self.amazon_buyer_id

class MessageThread(models.Model):
    buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE)
    thread_id = models.CharField(max_length=64, unique=True)
    last_updated = models.DateTimeField(default=timezone.now)
    is_closed = models.BooleanField(default=False)
    class Meta:
        db_table = 'app_messagethread'
        verbose_name = '消息线程'
        verbose_name_plural = '消息线程'
        app_label = 'app'  # 添加这一行

    def __str__(self):
        return self.thread_id
import uuid

class Message(models.Model):
    thread = models.ForeignKey(MessageThread, on_delete=models.CASCADE, related_name='messages')
    sender = models.CharField(max_length=16, choices=[('BUYER', '买家'), ('SELLER', '卖家')])
    message_id = models.CharField(max_length=64, unique=True)  # 亚马逊消息ID
    content = models.TextField()
    created_at = models.DateTimeField(default=timezone.now)
    is_read = models.BooleanField(default=False)
    
    # 新增字段：用于标识消息唯一性（避免重复同步）
    external_id = models.CharField(max_length=100, blank=True, null=True, db_index=True)
    synced_at = models.DateTimeField(auto_now_add=True, verbose_name="首次同步时间")

    class Meta:
        db_table = 'app_message'
        verbose_name = '消息'
        verbose_name_plural = '消息'
        app_label = 'app'  # 添加这一行
        constraints = [
            # 确保同一线程下不会重复同步相同external_id的消息
            models.UniqueConstraint(fields=['thread', 'external_id'], name='unique_thread_external_id')
        ]


class AmazonStore(models.Model):
    COUNTRY_CHOICES = [
        ('US', '美国'),
        ('CA', '加拿大'),
        ('MX', '墨西哥'),
        ('BR', '巴西'),
        ('ES', '西班牙'),
        ('UK', '英国'),
        ('DE', '德国'),
        ('FR', '法国'),
        ('IT', '意大利'),
        ('JP', '日本'),
        ('AU', '澳大利亚'),
        ('IN', '印度'),
        ('SG', '新加坡'),
        ('AE', '阿联酋'),
        ('SA', '沙特阿拉伯'),
        ('SE', '瑞典'),
        ('NL', '荷兰'),
        ('PL', '波兰'),
        ('EG', '埃及'),
        ('TR', '土耳其'),
    ]
    storetype_choice=[
         
            ('amazon','亚马逊店铺'),
            ('ebay','ebay店铺'),
            ('walmart','沃尔玛店铺'),
         

    ]
    storetype=models.CharField(max_length=50,choices=storetype_choice, verbose_name='店铺类型',default='')
    store_name = models.CharField(max_length=100, verbose_name='店铺名称')
    seller_id = models.CharField(max_length=100, verbose_name='卖家ID')
    account = models.CharField(max_length=100, verbose_name='账号')
    country = models.CharField(max_length=50, choices=COUNTRY_CHOICES, verbose_name='国家')
    sites = models.JSONField(default=list, verbose_name='站点')
    auth_status = models.CharField(max_length=20, default='pending', verbose_name='授权状态')
    store_status = models.CharField(max_length=20, default='active', verbose_name='店铺状态')
    last_auth_time = models.DateTimeField(null=True, blank=True, verbose_name='最后授权时间')
    refresh_token = models.TextField(null=True, blank=True, verbose_name='刷新令牌')
    access_token = models.TextField(null=True, blank=True, verbose_name='访问令牌')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    region = models.CharField(max_length=32, verbose_name='区域', default='北美洲')

    class Meta:
        verbose_name = '亚马逊店铺'
        verbose_name_plural = '亚马逊店铺'
        ordering = ['-created_at']
        db_table = 'app_amazon_store'

    def __str__(self):
        return f"{self.store_name} ({self.seller_id})"

    @property
    def app_config(self):
        """获取全局应用配置"""
        return AmazonAppConfig.get_config()

class AmazonAppConfig(models.Model):
    """亚马逊应用配置模型 - 全局单例配置"""
    app_name = models.CharField(max_length=100, verbose_name='应用名称', default='亚马逊应用')
    client_id = models.CharField(max_length=100, verbose_name='应用ID')
    client_secret = models.CharField(max_length=100, verbose_name='应用密钥')
    redirect_uri = models.CharField(max_length=200, verbose_name='回调地址')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '亚马逊应用配置'
        verbose_name_plural = '亚马逊应用配置'
        ordering = ['-created_at']
        db_table = 'app_amazon_app_config'

    def __str__(self):
        return self.app_name

    def save(self, *args, **kwargs):
        # 确保只有一个配置实例
        if not self.pk and AmazonAppConfig.objects.exists():
            raise ValueError('只能创建一个应用配置实例')
        super().save(*args, **kwargs)

    @classmethod
    def get_config(cls):
        """获取应用配置实例"""
        config = cls.objects.first()
        if not config:
            raise ValueError('请先在管理后台配置亚马逊应用信息')
        return config

class Product2(models.Model):
    name = models.CharField(max_length=100, verbose_name='产品名称')
    sku = models.CharField(max_length=50, unique=True, verbose_name='SKU')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    stock = models.IntegerField(default=0, verbose_name='库存')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

class EbayStore(models.Model):
    COUNTRY_CHOICES2 = [
        ('US', '美国'),
        ('CA', '加拿大'),
        ('MX', '墨西哥'),
        ('BR', '巴西'),
        ('ES', '西班牙'),
        ('UK', '英国'),
        ('DE', '德国'),
        ('FR', '法国'),
        ('IT', '意大利'),
        ('JP', '日本'),
        ('AU', '澳大利亚'),
        ('IN', '印度'),
        ('SG', '新加坡'),
        ('AE', '阿联酋'),
        ('SA', '沙特阿拉伯'),
        ('SE', '瑞典'),
        ('NL', '荷兰'),
        ('PL', '波兰'),
        ('EG', '埃及'),
        ('TR', '土耳其'),
    ]
    store_name = models.CharField(max_length=100, verbose_name='店铺名称')
    seller_id = models.CharField(max_length=100, verbose_name='卖家ID')
    account = models.CharField(max_length=100, verbose_name='账号')
    country = models.CharField(max_length=50, choices=COUNTRY_CHOICES2, verbose_name='国家')
    sites = models.JSONField(default=list, verbose_name='站点')
    auth_status = models.CharField(max_length=20, default='pending', verbose_name='授权状态')
    store_status = models.CharField(max_length=20, default='active', verbose_name='店铺状态')
    last_auth_time = models.DateTimeField(null=True, blank=True, verbose_name='最后授权时间')
    refresh_token = models.TextField(null=True, blank=True, verbose_name='刷新令牌')
    access_token = models.TextField(null=True, blank=True, verbose_name='访问令牌')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    region = models.CharField(max_length=32, verbose_name='区域', default='北美洲')

    class Meta:
        verbose_name = 'eBay店铺'
        verbose_name_plural = 'eBay店铺'
        ordering = ['-created_at']
        db_table = 'app_ebay_store'

    def __str__(self):
        return f"{self.store_name} ({self.seller_id})"

class ScheduledTask(models.Model):
    """定时任务模型"""
    TASK_TYPE_CHOICES = [
        ('amazon_data', '亚马逊数据下载'),
        ('ebay_data', 'eBay数据下载'),
        ('walmart_data', '沃尔玛数据下载'),
        ('price_monitor', '价格监控'),
        ('rank_monitor', '排名监控'),
    ]
    
    STATUS_CHOICES = [
        ('active', '启用'),
        ('inactive', '禁用'),
        ('running', '运行中'),
        ('error', '错误'),
    ]
    
    name = models.CharField('任务名称', max_length=100)
    task_type = models.CharField('任务类型', max_length=50, choices=TASK_TYPE_CHOICES)
    description = models.TextField('任务描述', blank=True)
    
    # 定时设置
    is_daily = models.BooleanField('每日执行', default=True)
    execution_times = models.JSONField('执行时间', default=list)  # 存储每天的执行时间，如 ["08:00", "14:00", "20:00"]
    start_hour=models.IntegerField('开始时间', default=0)

    # 任务状态
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='active')
    last_run = models.DateTimeField('最后执行时间', null=True, blank=True)
    next_run = models.DateTimeField('下次执行时间', null=True, blank=True)
    
    # 执行结果
    success_count = models.IntegerField('成功次数', default=0)
    error_count = models.IntegerField('失败次数', default=0)
    last_error = models.TextField('最后错误信息', blank=True)
    
    # 部门信息
    epid = models.CharField('部门编号', max_length=64, db_index=True, null=True, blank=True)
    
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        db_table = 'app_scheduled_task'
        verbose_name = '定时任务'
        verbose_name_plural = '定时任务'
        app_label = 'app'
     
    
    def __str__(self):
        return f"{self.name} ({self.get_task_type_display()})"
    
    def get_execution_times(self):
        """获取每日的3个执行时间点"""
        times = []
        for i in range(3):
            hour = (self.start_hour + i * 8) % 24
            times.append(f"{hour:02d}:00")
        return times
    
    def calculate_next_run(self):
        """计算下次执行时间"""
        from datetime import datetime, timedelta
        import pytz
        
        now = timezone.now()
        today = now.date()

        execution_times = []
        for i in range(3):
            hour = (self.start_hour + i * 8) % 24
            hour = (self.start_hour + i * 8) % 24
            execution_time = datetime.combine(today, datetime.min.time().replace(hour=hour, minute=0))
            execution_times.append(execution_time)
                
        for execution_time in sorted(execution_times):
            # execute_time_naive=timezone.make_naive(execution_time)
            if execution_time > now:
                return execution_time
        
        tomorrow = today + timedelta(days=1)
        first_hour = self.start_hour
        next_execution = datetime.combine(tomorrow, datetime.min.time().replace(hour=first_hour, minute=0))
        return pytz.timezone(timezone.get_current_timezone_name()).localize(next_execution)
    
    def save(self, *args, **kwargs):
        # 移除自动计算next_run的逻辑，由admin中的save_model方法处理
        if self.status == 'inactive':
            self.next_run = None
        super().save(*args, **kwargs)


class TaskExecutionLog(models.Model):
    """任务执行日志"""
    task = models.ForeignKey(ScheduledTask, on_delete=models.CASCADE, related_name='execution_logs')
    started_at = models.DateTimeField('开始时间', auto_now_add=True)
    finished_at = models.DateTimeField('结束时间', null=True, blank=True)
    status = models.CharField('状态', max_length=20, choices=[
        ('success', '成功'),
        ('error', '失败'),
        ('running', '运行中'),
    ])
    result = models.TextField('执行结果', blank=True)
    error_message = models.TextField('错误信息', blank=True)
    
    class Meta:
        db_table = 'app_task_execution_log'
        verbose_name = '任务执行日志'
        verbose_name_plural = '任务执行日志'
        app_label = 'app'
        ordering = ['-started_at']
    
    def __str__(self):
        return f"{self.task.name} - {self.started_at}"